<?php
App::uses('Sanitize','Utility');
class OrdersController extends AppController {	
	var $uses = array('Order','OrderDetail','OrderStatus','PaymentType','ShippingType','OrderShipping');
    public function index() {
		$conditions = array();
		$having = 1;
		$name = $payment_type_id = $shipping_type_id = $order_status_id = $delivery_date = $price_from = $price_to = '';		 
		if($this->request->is('get')){
			if(!empty($this->params->query['name'])){
				$name = Sanitize::escape($this->params->query['name']);
				$conditions['and']["Customer.name like"] = "%{$name}%";
			}
			if(!empty($this->params->query['payment_type_id'])){
				$payment_type_id = Sanitize::escape($this->params->query['payment_type_id']);
				$conditions['and']["payment_type_id"] = $payment_type_id;
			}
			if(!empty($this->params->query['shipping_type_id'])){
				$shipping_type_id = Sanitize::escape($this->params->query['shipping_type_id']);
				$conditions['and']["shipping_type_id"] = $shipping_type_id;
			}
			if(!empty($this->params->query['order_status_id'])){
				$order_status_id = Sanitize::escape($this->params->query['order_status_id']);
				$conditions['and']["order_status_id"] = $order_status_id;
			}
			if(!empty($this->params->query['delivery_date']['year']) && !empty($this->params->query['delivery_date']['month']) 
			&& !empty($this->params->query['delivery_date']['day'])){
				$delivery_date = date('Y-m-d',mktime(null,null,null,$this->params->query['delivery_date']['month'],$this->params->query['delivery_date']['day'],$this->params->query['delivery_date']['year']));
				$conditions['and']["delivery_date"] = $delivery_date;
			}
			if(!empty($this->params->query['price_from'])){
				$price_from = Sanitize::escape($this->params->query['price_from']);
				$having = 'sum(OrderDetail.price*OrderDetail.amount) >= '.$price_from;
			}
			if(!empty($this->params->query['price_to'])){
				$price_to = Sanitize::escape($this->params->query['price_to']);
				if(empty($having)){
					$having = 'sum(OrderDetail.price*OrderDetail.amount) <= '.$price_to;
				}
				else {
					$having .= ' and sum(OrderDetail.price*OrderDetail.amount) <= '.$price_to;
				}
			}
		}
		$this->paginate = array(
			'fields' => array('Order.total','Customer.name','PaymentType.name','ShippingType.name','OrderStatus.name','Order.created','Order.id','sum(OrderDetail.price*OrderDetail.amount) as total'),
			'conditions' => $conditions,
			'order'=>'Order.created desc',
			'limit'=>10,
			'recursive'=>0,
			'joins' => array(
				array(
					'table' => 'order_details',
					'alias' => 'OrderDetail',
					'type' => 'left',					
					'conditions'=> array('OrderDetail.order_id = Order.id'),
				),
			),
			'group' => array('Order.id having '.$having),			
		);
        $rs = $this->paginate('Order');
		$opt_payment = $this->PaymentType->find('list',array('fields'=>array('id','name')));
		$opt_shipping = $this->ShippingType->find('list',array('fields'=>array('id','name')));
		$opt_status = $this->OrderStatus->find('list',array('fields'=>array('id','name')));
		$this->set(compact('rs','name','payment_type_id','shipping_type_id','order_status_id','price_from','price_to','delivery_date','opt_payment','opt_shipping','opt_status'));
		if($this->request->is('ajax')){
			$this->layout = 'ajax';
			$this->render('ajax_search');
		}
    }
	
	public function detail($id = null){
		if($id == null) $this->redirect('.');
		$item = $this->Order->find('first',array(			
			'conditions'=>array('Order.id'=>$id),
			'recursive'=>1,
		));
		
		$order_status = $this->OrderStatus->find('list');
		$this->set(compact('item','order_status'));
	}
	
	public function add() {
        if ($this->request->is('post')) {
            $this->Order->create();
            if ($this->Order->save($this->request->data,true)) {
                $this->Session->setFlash(__('Đã được lưu'));
                $this->redirect(array('action' => '.'));
            } else {
                $this->Session->setFlash(__('Có lỗi, không lưu được, xin thử lại'));
            }
        }
		$opt_payment = $this->PaymentType->find('list',array('fields'=>array('id','name')));
		$opt_shipping = $this->ShippingType->find('list',array('fields'=>array('id','name')));
		$opt_status = $this->OrderStatus->find('list',array('fields'=>array('id','name')));
		$this->set(compact('opt_payment','opt_shipping','opt_status'));
    }

    public function edit($id = null) {
        $this->Order->id = $id;
        if (!$this->Order->exists()) {
            throw new NotFoundException(__('Không tìm thấy'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Order->save($this->request->data)) {
                $this->Session->setFlash(__('Đã được lưu'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Có lỗi, không lưu được, xin thử lại'));
            }
        } else {
            $this->request->data = $this->Order->read(null, $id);			
        }
		$opt_payment = $this->PaymentType->find('list',array('fields'=>array('id','name')));
		$opt_shipping = $this->ShippingType->find('list',array('fields'=>array('id','name')));
		$opt_status = $this->OrderStatus->find('list',array('fields'=>array('id','name')));
		$this->set(compact('opt_payment','opt_shipping','opt_status'));
    }
	
	public function change_order_status(){
		$this->render(false);
		if(!empty($this->data)){
			$this->Order->id = $this->data['Order']['id'];
			$this->Order->saveField('order_status_id',$this->data['Order']['order_status_id']);
		}
		$this->redirect('.');
	}
	
	public function delete($id = null) {
		if($id==null) die("No ID received");		
		if($this->Order->delete($id)==false){
			$this->Session->setFlash('Bị lỗi không xóa được');
		}
		else {
			$this->OrderDetail->deleteAll(array('order_id'=>$id));
			$this->OrderShipping->deleteAll(array('order_id'=>$id));
			$this->Session->setFlash('Item đã được xóa khỏi danh sách');
		}
		$this->redirect(array('action'=>'index'));
    }
	
	public function show_order_detail(){
		
	}
}
